//
//  HMRefreshControl.swift
//  MyWeibo
//
//  Created by apple on 16/4/24.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

//控件状态的枚举数组
enum HMRefreshControlState:Int{
    //默认状态
    case Normal = 0
    //松手就去刷新状态
    case Pulling = 1
    //刷新中状态
    case Refreshing = 2
    
}


//设定刷新控件的高度
private let HMRefreshControlH:CGFloat = 50

class HMRefreshControl: UIControl {

    //判断当前控件状态
    var hmState: HMRefreshControlState = .Normal {
        
        didSet{
            
            switch hmState{
                
                
            case .Pulling:
                
                //更改箭头方向
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            
                //更改文字为正在刷新
                msgLabel.text = "开始加载..."
            case .Refreshing:
                
                //箭头消失
                arrowImage.hidden = true
                
                //菊花转起来
                indecatorView.startAnimating()
                //更改加载文字
                msgLabel.text = "客观稍后，正在努力加载"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    //将tableView的内容再往下移动
                    self.tableView?.contentInset.top = self.tableView!.contentInset.top + HMRefreshControlH
                })
                
                //调用刷新方法
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
                
            case .Normal:
                
                //菊花停止旋转 
                indecatorView.stopAnimating()
                //显示箭头  原来的方向
                arrowImage.hidden = false
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.arrowImage.transform = CGAffineTransformIdentity
                })
                
                //更改字体等待加载
                msgLabel.text = "等待加载..."
                
                // 如果之前是刷新中的状态，那么进入到Normal状态就减去顶部多出来的滑动距离
                if oldValue == .Refreshing {
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        
                        self.tableView?.contentInset.top = self.tableView!.contentInset.top - HMRefreshControlH
                        
                    })
                    
                }
                
                
            }
        }
   
    }
    
    
    //当前控件的父控件
    var tableView:UIScrollView?
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    func setupUI(){
        
        //设置背景颜色
        backgroundColor = UIColor.yellowColor()
        //设置高度
        self.frame.size.height = HMRefreshControlH
        self.frame.size.width = SCREENW
        //讲刷新控件添加到tableview的最上面
        self.frame.origin.y = -HMRefreshControlH
        
        
        //添加控件
        self.addSubview(arrowImage)
        self.addSubview(msgLabel)
        self.addSubview(indecatorView)
        
        
        //添加约束
        arrowImage.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
        }
        msgLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerY.equalTo(arrowImage)
            
            make.leading.equalTo(arrowImage.snp_trailing)
        }
        
        indecatorView.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(arrowImage)
        }
    }
        //结束刷新方法
        func endRefreshing(){
            
            hmState = .Normal
            
        }

        //将要被添加到一个父控件上的时候就会调用
    
        override func willMoveToSuperview(newSuperview: UIView?){
            
            //调用父类
            super.willMoveToSuperview(newSuperview)
            //为kvo准备观察者
            guard let tableView = newSuperview where tableView.isKindOfClass(UIScrollView.self) else{
                return
            }
            //强转成scrollView类
            self.tableView = tableView as? UIScrollView
            //设置宽度
            self.frame.size.width = tableView.frame.width
            
            // 如果使用 KVO：我们需要监听tableView的 contentOffset，就需要给 tableView添加一个观察者
            tableView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
            
        }
        // 当观察的对象身上的属性发生改变的时候，就会回调这个方法
        override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
            //取到偏移量
            let contentOffset = self.tableView!.contentOffset
            
            //取到当前界面的y值
            let conditionValue = -tableView!.contentInset.top - HMRefreshControlH

            //拖动状态判断
            if tableView!.dragging {//如果拖动
                //偏移量小于y值得时候代表界面已经完全显示出来了
                if contentOffset.y < conditionValue && hmState == .Normal{
                   hmState = .Pulling
                }else{
                    
                    //偏移量大于y的时候代表界面还没有完全显示出来
                    if contentOffset.y > conditionValue && hmState == .Pulling{
                        hmState = .Normal
                    }
                }
                
            }else{//如果没有拖动  或者松手  检查加载状态
                
                
                if hmState == .Pulling{
                    
                    print("控件进行刷新中")
                    // 并且当前状态是松手就去刷新的话，就进行刷新中的状态
                    hmState = .Refreshing
                }
   
            }
        }
    
    
   //移除观察者
    deinit {
        tableView?.removeObserver(self, forKeyPath: "contentOffset")
    }

    
    //懒加载箭头
    
    private lazy var arrowImage:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //懒加载菊花
    private lazy var indecatorView:UIActivityIndicatorView = UIActivityIndicatorView()
    
    //懒加载提示label
    private lazy var msgLabel:UILabel = {
        
       let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 12)
        
        label.text = "啦啦啦啦"
        
        return label
    }()
    
}
